package com.iflytek.cosmo.ocr.support.license.spring;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

import com.iflytek.cosmo.ocr.support.license.LicenseManager;
import com.iflytek.cosmo.ocr.support.license.server.ServerLicense;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.ResourceUtils;

/**
 *
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/8/2
 */
public class LicenseCheckerApplicaitonRunListener implements SpringApplicationRunListener {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected static final String AUTH_PATH = "./view-ocr-server/src/main/resources/data/serverAuth.txt";

    private final SpringApplication application;
    private final String[] args;
    private LicenseManager manager;

    public LicenseCheckerApplicaitonRunListener(SpringApplication sa, String[] args) {
        this.application = sa;
        this.args = args;
    }

    @Override
    public void starting() {
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
    }

    @Override
    public void finished(ConfigurableApplicationContext context, Throwable exception) {
        LicenseManager manager = context.getBean(LicenseManager.class);

        // 如果是服务器环境(java -jar 启动)则进行授权校验
        if (runInServer() || true) {
            // 服务器授权
            String authInfo = null;
            try {
                authInfo = readAuthInfo();
            }
            catch (IOException e) {
                throw new RuntimeException("读取授权文件失败", e);
            }
            logger.info("服务器授权文件内容: {}", authInfo);

            ServerLicense license = manager.decodeServer(authInfo);
            logger.info("服务器授权信息: {}", license);
            if (license == null || !license.valid()) {
                throw new RuntimeException("服务器未授权");
            }
        }
    }

    public boolean runInServer() {
        URL location = LicenseCheckerApplicaitonRunListener.class.getProtectionDomain().getCodeSource().getLocation();
        return location.toString().startsWith("jar:");
    }

    public static String readAuthInfo() throws IOException {
        // 本地开发调用
        File file = ResourceUtils.getFile(AUTH_PATH);
        if (!file.exists()) {
            // 服务器运行时调用
            FileSystemResource systemResource = new FileSystemResource(
                    System.getProperty("iflytek.dir.data") + "/serverAuth.txt");
            file = systemResource.getFile();
        }

        if (file != null) {
            System.out.println("读取授权文件 " + file.getAbsolutePath());
        }

        StringBuilder resultStringBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.defaultCharset()))) {
            String line;
            while ((line = br.readLine()) != null) {
                resultStringBuilder.append(line).append("\n");
            }
        }
        return resultStringBuilder.toString();
    }
}
